package com.light.thread;

import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.function.Consumer;

/**
 * 创建task工具类
 */
public class FxTask {
    public static final Logger LOGGER = LoggerFactory.getLogger(FxTask.class);

    public static <T> Task<T> createTask(long startTime, String message, Run run, RunSuccess success, RunFail fail) {
        return new Task<>() {
            @Override
            protected T call() throws Exception {
                LOGGER.info("Task {} 开始执行", message);
                run.run();
                return null;
            }

            @Override
            protected void succeeded() {
                super.succeeded();
                if (null != success) {
                    success.run();
                }
                LOGGER.info("Task {} 执行成功，耗时 {} ms", message, System.currentTimeMillis() - startTime);
            }

            @Override
            protected void failed() {
                super.failed();
                if (null != fail) {
                    fail.run();
                }
                LOGGER.info("Task {} 执行失败，耗时 {} ms", message, System.currentTimeMillis() - startTime);
            }
        };
    }

    public static <T> Task<T> createTaskBack(long startTime, String message, RunBack<T> runBack, Consumer<T> success, Consumer<T> fail) {
        return new Task<>() {
            @Override
            protected T call() throws Exception {
                LOGGER.info("Task {} 开始执行", message);
                return runBack.get();
            }

            @Override
            protected void succeeded() {
                super.succeeded();
                Optional.of(success).ifPresent(success -> success.accept(getValue()));
                LOGGER.info("Task {} 执行成功，耗时 {} ms", message, System.currentTimeMillis() - startTime);
            }

            @Override
            protected void failed() {
                super.failed();
                Optional.of(fail).ifPresent(fail -> fail.accept(getValue()));
                LOGGER.info("Task {} 执行失败，耗时 {} ms", message, System.currentTimeMillis() - startTime);
            }
        };
    }
}
